﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate.Connection;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHCfg = NHibernate.Cfg;

namespace InnovTech.Persistence.NHibernate.Test
{
    public class TestDababaseInfo : INHDatabaseInfo
    {

        public string DBPath
        {
            get;
            set;
        }
        public System.Collections.Generic.Dictionary<string, string> GetConfigurationProperties()
        {
            Dictionary<string, string> sqlCeProperties = new Dictionary<string, string>();
            sqlCeProperties.Add(NHCfg.Environment.Dialect, typeof(MsSqlCeDialect).AssemblyQualifiedName);
            sqlCeProperties.Add(NHCfg.Environment.ConnectionDriver, typeof(SqlServerCeDriver).AssemblyQualifiedName);
            sqlCeProperties.Add(NHCfg.Environment.ConnectionProvider, typeof(DriverConnectionProvider).AssemblyQualifiedName);
            //to avoid the Bug "null identity" using the following settings for ReleaseConnections
            //http://stackoverflow.com/questions/2361730/assertionfailure-null-identifier-fluentnh-sqlserverce
            sqlCeProperties.Add(NHCfg.Environment.ReleaseConnections, "on_close");
            return sqlCeProperties;
        }

        public Action<TMappingTarget> GetMappingAction<TMappingTarget>()
        {
            return new Action<TMappingTarget>(target =>
            {
                NHCfg.Configuration config = target as NHCfg.Configuration;
                if (config != null)
                {
                    config.AddAssembly(typeof(TestBuilder).Assembly);
                }
            });
        }

        public string GetConnectionString()
        {
            string dbName = string.IsNullOrWhiteSpace(DBPath) ? "Test.sdf" : DBPath;
            string dbPath = Path.Combine(Directory.GetCurrentDirectory(), dbName);
            return "Data Source=" + dbPath;
        }
    }
}
